package pers.apricot.config

import groovy.transform.CompileStatic
import org.apache.http.HttpStatus
import org.springframework.stereotype.Component
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpSession

@CompileStatic
@Component
class LoginValidateInterceptor extends HandlerInterceptorAdapter {

    @Override
    boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession()
        Boolean isAuthenticated = session.getAttribute("userCode")
        if (!isAuthenticated) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED)
            response.sendRedirect("/")
            return false
        }
        return true
    }
}
